package com.framework.webxml.controller;

import com.framework.webxml.bean.User;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/info")
    public String info() {
        User user = new User();
        user.setId("1");
        user.setName("张三");
        user.setAge(18);
        return user.toString();
    }

    @GetMapping("/userinfo")
    public String userinfo() {
        return "userinfo";
    }

    @PostMapping("/json")
    public String json(@RequestBody User user) {
        return user.toString();
    }

    @GetMapping("/cookie")
    public String cookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("key", "value");
        response.addCookie(cookie);
        return "cookie save";
    }

    @GetMapping("/cookie2")
    public String cookie2(HttpServletResponse response) {
        // 使用 jakarta.servlet.http.Cookie
        Cookie cookie = new Cookie("key", "value");
        cookie.setMaxAge(3600); // 设置过期时间（秒）
        cookie.setPath("/");    // 设置Cookie路径
        response.addCookie(cookie);
        return "cookie save";
    }

    @GetMapping("/request")
    public String request(HttpServletRequest request) {
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        return "request:" + name + "," + age;
    }

    @GetMapping("/session")
    public String session(HttpSession session) {
        Object name = session.getAttribute("name");
        return "session:" + name;
    }

    // Spring 已经将其加入到IOC容器中
    @Autowired
    private ServletContext servletContext;

    @GetMapping("/application")
    public String application(HttpServletRequest request, HttpSession session) {
        // 方式一：通过请求域获取
        ServletContext servletContext1 = request.getServletContext();
        // 方式二：通过会话域获取
        ServletContext servletContext2 = session.getServletContext();
        System.out.println(servletContext1 == servletContext2);
        System.out.println(servletContext2 == servletContext);

        return "application";
    }


}
